/*
 * $Id: JsonRpcResponse.java 50456 2007-03-28 21:22:41Z jdamick $
 *
 * Copyright 2006- Revolution Health Group.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Revolution Health Group.  (Confidential Information).
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license 
 * agreement you entered into with Revolution Health Group.
 *
 */
package org.javason.jsonrpc.impl;

import static org.javason.jsonrpc.JsonRpcConstants.ERROR;
import static org.javason.jsonrpc.JsonRpcConstants.ID;
import static org.javason.jsonrpc.JsonRpcConstants.RESULT;

import net.sf.json.JSONException;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.javason.json.BeanToJsonSerializer;
import org.javason.jsonrpc.JsonRpcError;

public class JsonRpcResponse {
	private JSONObject _responseObject = new JSONObject();

	public JsonRpcResponse(Object id, Object result, Object error) throws JSONException {
		Object jsonResult = null;
		if (result != null) {
			jsonResult = BeanToJsonSerializer.serialize(result);
		}
		
		_responseObject.put(RESULT, getPossibleNullObject(jsonResult));
		if (error != null && error instanceof JsonRpcError) {
			_responseObject.put(ERROR, ((JsonRpcError)error).toJSON());	
		}
		_responseObject.put(ID, getPossibleNullObject(id));
	}
	
	public String toString() {
		return _responseObject.toString();
	}
	
	private Object getPossibleNullObject(Object jsonObject) {
		return (jsonObject != null ? jsonObject : JSONNull.getInstance());
	}
}
